<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--      筛选-->
      <!--      分栏24占满 -->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
          <el-form-item label="评论用户" prop="userId">
            <el-select
              style="width: 240px"
              v-model="queryParams.userId"
              filterable
              remote
              reserve-keyword
              placeholder="请输入用户昵称"
              :remote-method="remoteMethod"
              :loading="loading2">
              <el-option
                v-for="item in options"
                :key="item.userId"
                :label="item.nickName"
                :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="del_flag">
            <el-select
              v-model="queryParams.del_flag"
              placeholder="用户状态"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in sys_normal_disable"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="关键字" prop="content">
            <el-input
              v-model="queryParams.content"
              placeholder="请输入关键字"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="发布时间">
            <el-date-picker
              v-model="dateRange"
              style="width: 240px"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
            >删除</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="talkList"  @selection-change="handleSelectionChange" >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="用户昵称" align="center" prop="user.nickName" v-if="columns[0].visible" />

          <el-table-column label="用户头像" align="center"  width="80" v-if="columns[1].visible"  >
            <template slot-scope="scope">
              <el-avatar  size="medium" :src="scope.row.user&&setUrl(scope.row.user.avatar)"></el-avatar>
            </template>
          </el-table-column>
          <el-table-column label="发布内容" align="center" key="content" prop="content" v-if="columns[2].visible" :show-overflow-tooltip="true"  width="160" />
          <el-table-column label="点赞量" align="center" key="thumbsNum" prop="thumbsNum" v-if="columns[3].visible" :show-overflow-tooltip="true"  />
          <el-table-column label="分类名称" align="center" key="typeName" prop="typeName" v-if="columns[4].visible" :show-overflow-tooltip="true"  />

          <el-table-column label="是否下架" align="center" key="delFlag" v-if="columns[5].visible">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.delFlag"
                :active-value=1
                :inactive-value=0
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="发布时间" align="center" prop="createTime" v-if="columns[6].visible" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope" v-if="scope.row.userId !== 1">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-s-comment"
                @click="toComment(scope.row)"
              >评论</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>

          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form  ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-row :span="12">
            <el-col :span="12">
              <el-form-item label="分类" prop="typeId">
                <el-select  size="mini" v-model="form.typeId" placeholder="请选择分类">
                  <el-option
                    v-for="item in typeList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态">
                <el-radio-group v-model="form.delFlag">
                  <el-radio
                    v-for="dict in sys_normal_disable"
                    :key="dict.value"
                    :label="dict.value"
                  >{{dict.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row>
          </el-row>
          <el-row :span="24">
            <el-form-item label="图片">
              <el-upload
                action=""
                list-type="picture-card"
                :file-list="fileList"
                :on-preview="handlePictureCardPreview"
                :httpRequest="httpRequest">
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{file}">
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="setUrl(file.url)" alt=""
                  >
                  <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span
                    class="el-upload-list__item-delete"
                    @click="handleDownload(file)"
                  >
                    <i class="el-icon-download"></i>
                  </span>
                  <span
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
                </div>
              </el-upload>
            </el-form-item>
          </el-row>
          <el-row :span="24">
            <el-form-item prop="content" label="内容">
              <el-input autosize v-model="form.content" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-row>
        </el-row>
      </el-form>
      <div  slot="footer" class="dialog-footer">
        <el-button  type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>

  </div>
</template>

<script>
import { addType, changeTypeStatus, delType, listType, updateType } from '@/api/problemType'
import { listUserByUserNickName } from '@/api/talkComment'
import { listTalk, upload, typeList, changeStatus, updateTalk, delTalk, addTalk } from '@/api/talk'
import * as qiniu from  "qiniu-js"
import { getUploadToken } from '@/api/system/common'
import crypto from "crypto";
export default {
  name: "Talk",
  data() {
    return {
      sys_normal_disable:[
        {
          value:0,
          label:"正常"
        },
        {
          value:1,
          label:"下架"
        }
      ],
      disabled:false,
      // 遮罩层
      loading: true,
      loading2:false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      talkList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dialogVisible:false,
      dialogImageUrl:null,
      multiple:true,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      //分类列表
      typeList:[],
      //选中列表
      ids:[],
      userName:undefined,
      userByName:undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: undefined,
        content:undefined,
        del_flag:undefined
      },
      // 列信息
      columns: [
        { key: 0, label: `用户昵称`, visible: true },
        { key: 1, label: `用户头像`, visible: true },
        { key: 2, label: `发布内容`, visible: true },
        { key: 3, label: `点赞量`, visible: true },
        { key: 4, label: `分类名称`, visible: true },
        { key: 5, label: `是否下架`, visible: true },
        { key: 6, label: `发布时间`, visible: true }

      ],
      // 表单校验
      rules: {
        typeId:[
          { required: true, message: "分类不能为空", trigger: "blur" },

        ],
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" },
        ]
      },
      //用户列表
      options:[],
      fileList:[]
    };
  },
  watch: {

  },
  created() {
    this.getList();
    typeList().then(res=>{
      this.typeList = res.data
    })
  },
  methods: {
    /** 查询帖子列表 */
    getList() {

      this.loading = true;
      listTalk(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          // console.log(response)
          this.talkList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 用户状态修改 */
    handleStatusChange(row) {
      let text = row.delFlag === 1 ? "下架" : "恢复";
      this.$modal.confirm('确认'+text+'帖子吗？').then(function() {
        return changeStatus(row.id, row.delFlag);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.delFlag = row.delFlag === 0 ? 1 : 0;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /**  表单重置 */
    reset() {
      this.form = {
        id: undefined,
        content: undefined,
        typeId: undefined,
        delFlag:0,
        pictrueList:[],
      };
      this.fileList = []
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.title = "添加帖子";
      this.open = true;
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.multiple = !selection.length;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const Ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除！（评论，图片都会不可逆转的被删除）').then(function() {
        return delTalk(Ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.form = row;
      this.fileList = []
      if(row.pictrueList!=null){
        row.pictrueList.forEach((item,index)=>{
          this.fileList.push({name:index,url: item})
        })
      }
      this.open = true;
      this.title = "修改帖子";
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.pictrueList = []
          this.fileList.forEach(item=>{
            this.form.pictrueList.push(item.url)
          })

          if (this.form.id != undefined) {

            updateTalk(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTalk(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    //远程查询用户
    remoteMethod(query){
      if (query !== '') {
        this.loading2 = true;
        listUserByUserNickName({ nickName: query }).then(res => {
          this.options = res.data;
          this.loading2 = false;
        })
      }
    },
    //图片删除
    handleRemove(file) {
      this.fileList = this.fileList.filter(item=>item.url!=file.url)
    },
    //图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //图片下载
    handleDownload(file) {
    },
    //图片上传
    async httpRequest({ file }){
      // console.log(file)
      // // 创建一个 FormData 对象，用于构建请求参数
      // const formData = new FormData();
      // formData.append('file', file); // 将文件添加到 FormData 中
      //
      // upload(formData).then(res=>{
      //   this.fileList.push({url:res.url})
      // })
      let md5 = await this.computeFileMD5(file);
      const name = 'talk/' + md5 + '.' + file.name.split('.').pop()
      // console.log(name)
      const  res = await getUploadToken()
      const config = {
        useCdnDomain: true,
        region: qiniu.region.z2
      };
      const observable = qiniu.upload(file, name, res.data,config)
      observable.subscribe(
        {
          next(res){
            // ...
          },
          error(err){
            // ...
            console.error(err)
          },
          complete:(res)=>{
            // ...
            // console.log(res)
            this.fileList.push({url:'https://qiniu.xlfdeblog.top/' + res.key})
          }
        }
      ) // 上传开始

      //阻止默认上传行为
      return false;
    },
    setUrl(url){
      return this.getUrl(url)
    },
    toComment(row){
      this.$router.push({
        path: '/talkComment',
        query: {
          talkId: row.id
        }
      })
    },
    // 计算文件的 MD5 值
    async computeFileMD5(file) {
      const buffer = await this.readFileAsBuffer(file);
      const hash = crypto.createHash("md5");
      hash.update(buffer);
      return hash.digest("hex");
    },

    // 将文件读取为 Buffer
    async readFileAsBuffer(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onloadend = () => {
          resolve(Buffer.from(reader.result));
        };
        reader.onerror = reject;
        reader.readAsArrayBuffer(file);
      });
    },

  }
};
</script>
<style>

</style>
